﻿using Api.Application.Command.Leave;
using AutoMapper;
using Domain;
using ErrorCode;
using Infrastructure;
using MediatR;

namespace Api.Application.Handler.Leave
{
    public class AddLeaveHandler : IRequestHandler<AddLeaveCommand, ApiResult<int>>
    {
        private readonly IBase<UserModel> userRepo;
        private readonly IBase<LeaveModel> leaveRepo;
        private readonly IMapper mapper;

        public  AddLeaveHandler(IBase<UserModel> userRepo,IBase<LeaveModel> leaveRepo,IMapper mapper)
        {
            this.userRepo = userRepo;
            this.leaveRepo = leaveRepo;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(AddLeaveCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            var leave = mapper.Map<LeaveModel>(request);
            var user = userRepo.GetAll().Where(x => x.IsDeleted == false);
            leave.CrearName = "张三";
            leave.CrearTime=DateTime.Now;
            
            leave.ApprovalState = false;
            if(leave.LeaveEndTime<leave.LeaveStartTime)
            {
                result.Code = ApiEnum.Fail;
                result.Msg = "请假结束时间必须大于请假开始时间";
                return Task.FromResult(result);
            }
            var r=leaveRepo.Add(leave).Result;
            if(r>0)
            {
                result.Code = ApiEnum.OK;
                result.Data = r;
                result.Msg = "请假审批添加成功";
            }
            else
            {
                result.Code = ApiEnum.Fail;
                result.Data = r;
                result.Msg = "请假审批添加失败";
            }
            return Task.FromResult(result);
        }
    }
}
